package top.yunmouren.areamusic.player;

import org.bukkit.entity.Player;
import org.bukkit.metadata.FixedMetadataValue;
import org.bukkit.metadata.MetadataValue;
import top.yunmouren.areamusic.AreaMusic;
import top.yunmouren.areamusic.config.Priority;
import top.yunmouren.areamusic.exception.PlayerNullException;
import top.yunmouren.areamusic.music.MusicTag;

import java.util.List;

public class PlayerBridge {
    private final AreaMusic plugin;
    private final Player player;

    public PlayerBridge(Player player, AreaMusic plugin) throws PlayerNullException {
        this.plugin = plugin;
        if (player == null) {
            throw new PlayerNullException();
        } else {
            this.player = player;
        }
    }

    public void setPlayerMusicTags(MusicTag musicTag) {
        if (musicTag != null) {
            String musicId = musicTag.getMusicId();
            String musicUUID = musicTag.getMusicUUID();
            String musicURL = musicTag.getMusicURL();
            Priority priority = musicTag.getPriority();
            String fromWorld = musicTag.getFromWorld();
            String areaId = musicTag.getAreaUUID();
            String expiredTime = musicTag.getExpiredTime().toString();
            if (musicId != null && !musicId.equals("") && !expiredTime.equals("")) {
                this.clearPlayerMusicTag();
                this.player.setMetadata("area-music-tag", new FixedMetadataValue(this.plugin, musicId + "|" + musicUUID + "|" + musicURL + "|" + priority.name() + "|" + fromWorld + "|" + areaId + "|" + expiredTime));
            }
        }
    }

    public MusicTag getPlayerMusicTag() {
        List<MetadataValue> valueList = this.player.getMetadata("area-music-tag");
        if (valueList.size() == 0) {
            return null;
        } else {
            String originSrc = ((MetadataValue)valueList.get(0)).asString();
            String[] splitData = originSrc.split("[|]");
            return splitData.length != 7 ? null : MusicTag.builder().musicId(splitData[0]).musicUUID(splitData[1]).musicURL(splitData[2]).priority(Priority.valueOf(splitData[3])).fromWorld(splitData[4]).areaUUID(splitData[5]).expiredTime(Long.parseLong(splitData[6])).build();
        }
    }

    public void clearPlayerMusicTag() {
        this.player.removeMetadata("area-music-tag", this.plugin);
    }

    public Player getPlayer() {
        return this.player;
    }
}
